package com.xnf.wemedia.gateway.filter;

import com.xnf.wemedia.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Created by xnf on 2022/3/2.
 */
@Component
@Log4j2
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("filter");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        System.out.println(request.getURI().getPath());
        if (request.getURI().getPath().contains("/login/in")) {
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            log.info("token isEmpty ,HttpStatus.UNAUTHORIZED ", HttpStatus.UNAUTHORIZED, request.getURI());
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }

        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int result = AppJwtUtil.verifyToken(claims);
            System.out.println(result);
            if (result == -1 || result == 0) {
                Integer id = (Integer) claims.get("id");
                log.info("find userid:{} from uri:{}", id, request.getURI());
                ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                    httpHeaders.add("userId", id + "");
                   // httpHeaders.add("token", token);
                }).build();
                exchange.mutate().request(serverHttpRequest).build();
            } else {
                log.info("HttpStatus.UNAUTHORIZED ", HttpStatus.UNAUTHORIZED, request.getURI());
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                response.setComplete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("HttpStatus.UNAUTHORIZED ", HttpStatus.UNAUTHORIZED, request.getURI());
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
